package org.ezplatform.office.meeting.setting.serve.service;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.ezplatform.component.permission.service.CmpPermissionService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.meeting.info.service.QSMeetingService;
import org.ezplatform.office.meeting.setting.boardroom.entity.BoardroomSet;
import org.ezplatform.office.meeting.setting.boardroom.service.BoardroomSetService;
import org.ezplatform.office.meeting.setting.serve.dao.ServeSetDao;
import org.ezplatform.office.meeting.setting.serve.entity.ServeSet;
import org.ezplatform.util.SqlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServeSetService extends BaseService<ServeSet, String>{
	
	private final Logger logger = LoggerFactory.getLogger(ServeSetService.class);
    @Autowired
    private ServeSetDao dao;
    @Lazy
    @Autowired
    private BoardroomSetService boardroomSetService;
    @Lazy
    @Autowired
	private CmpPermissionService cmpPermissionService;
    
    @Override
    protected JpaBaseDao<ServeSet, String> getEntityDao() {
        return dao;
    }
    
    /**
     * 查询列表数据
     * @param localPageable
     * @param corpId
     * @param name
     * @return
     */
    public Page getServeSetList(Pageable localPageable, String corpId, String name,WebUser webUser) {
    	
    	logger.debug("-----getServeSetList----");
    	
        Map<String, Object> paramMap = new HashMap<String, Object>();
        StringBuffer sql = new StringBuffer();
        sql.append(" select omss.id,omss.name,omss.sort_no,omss.is_init");
        sql.append(" from oa_meeting_serve_set omss");
        sql.append(" where omss.corp_id=:corpId");
        paramMap.put("corpId", corpId);
        if(StringUtils.isNotBlank(name)){
        	name=SqlUtils.escapeNormalChars(name);
            sql.append(" and omss.name like :name "+SqlUtils.getSQLEscape(name));
            paramMap.put("name", "%"+name+"%");
        }
        String perSql = cmpPermissionService.getBusinessScopeSql("omss", webUser, "meeting:service:03");
        logger.debug("---perSql:"+perSql);
		sql.append(perSql);
		
        List localList = new ArrayList();
        String sqlStr = PropertyFilter.getSqlByFilterAndPageable("omss", sql.toString(), "omss.sort_no asc,omss.createdDate desc", localList, localPageable);
        Page<Map> localPage = this.findByPageNativeSQL(localPageable, sqlStr, paramMap);
        
        return localPage;
    }

    /**
     * 验证
     * @param id
     * @param checkdata
     * @param type
     * @param corpId
     * @return
     */
    public String checkServeSet(String id, String checkdata, int type, String corpId) {
        String msg = "";
        List<ServeSet> list = new ArrayList<ServeSet>();
        if (type == 1) {// 验证名称
            if (StringUtils.isNotBlank(id)) {// 编辑
                list = this.dao.getServeSetByName(id, checkdata, corpId);
            } else {// 新建
                list = this.dao.getServeSetSetByName(checkdata, corpId);
            }
        }
        if (list != null && list.size() > 0) {
            msg = this.getCheckMsgStr(type);
        }
        return msg;
    }
    
    /**
     * 验证报错返回msg信息
     * 
     * @param type
     * @return
     */
    private String getCheckMsgStr(int type) {
        String msg = "";
        switch (type) {
        case 1:
            msg = "您输入的服务名称已存在";
            break;
        default:
            msg = "";
            break;
        }
        return msg;
    }

    /**
     * 查询会议服务树数据
     * @param request
     * @param corpId
     * @return
     */
    public String getServeTreeData(HttpServletRequest request, String corpId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();

        String sql = "select id,name from oa_meeting_serve_set ";
        sql += " where corp_id = :corpId ";
        paramMap.put("corpId", corpId);
        sql += " ORDER BY sort_no asc,createdDate desc";

        List menuTree = super.getQueryByNativeSQL(sql.toString(), paramMap).getResultList();

        StringBuffer str = new StringBuffer("");
        str.append("[");
        for (int i = 0; i < menuTree.size(); i++) {
            str.append((new StringBuilder()).append("{\"id\":\"").append(((Object[]) menuTree.get(i))[0])
                    .append("\",\"pId\":\"").append("\",\"name\":\"").append(((Object[]) menuTree.get(i))[1])
                    .append("\"},"));
        }

        String str1 = str.toString();
        if (str1.endsWith(","))
            str1 = str1.substring(0, str1.length() - 1);
        str1 = (new StringBuilder()).append(str1).append("]").toString();
        return str1;
    }
    
    /**
     * 查询会议服务树数据
     * @param request
     * @param corpId
     * @return
     */
    public List<Map> getServeSetList(HttpServletRequest request, String corpId) {
        Map<String, Object> params = new HashMap<>();
        params.put("corpId", corpId);
        String sql = "select id value,name text from oa_meeting_serve_set ";
        sql += " where corp_id = :corpId ";
        sql += " ORDER BY sort_no asc,createdDate desc";

        List<Map> list = super.findByListNativeQuery(sql, "", params);
        return list;
    }
    
    /**
     * 查询会议申请选中的会议服务
     * @param request
     * @param meetingServe
     * @return
     */
    public List<Map> getServeSetCheckList(String ids) {
        List<Map> list = new ArrayList<>();
        if(StringUtils.isNotBlank(ids)){
            String[] strArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            for(String id : strArr){
                idList.add(id);
            }
            Map<String, Object> params = new HashMap<>();
            params.put("ids", idList);
            String sql = "select id value,name text from oa_meeting_serve_set ";
            sql += " where id in (:ids) ";
            sql += " ORDER BY sort_no asc,createdDate desc";
            
            list = super.findByListNativeQuery(sql, "", params);
        }
        return list;
    }

    /**
     * 查询会议服务集合
     * @param meetingServe
     * @return
     */
    public List<ServeSet> getServeSetListByIds(String ids) {
        List<String> list = new ArrayList<String>();
        String[] strArr = ids.split(",");
        for(String id : strArr){
            list.add(id);
        }
        return this.dao.getServeSetListByIds(list);
    }

    public String getBoardRoomServeTreeData(HttpServletRequest request, String corpId, String boardroomId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        
        if(StringUtils.isEmpty(boardroomId)){
            return "[]";
        }
        
        BoardroomSet boardroomSet = this.boardroomSetService.findOne(boardroomId);
        List<String> msList = new ArrayList<String>();
        if(boardroomSet != null){
            String meetingServer = boardroomSet.getMeetingServe();
            if(StringUtils.isNoneEmpty(meetingServer)){
                for(String ms:meetingServer.split(",")){
                    msList.add(ms);
                }
            }
        }
        if(msList!=null &&msList.size()>0){
            String sql = "select id,name from oa_meeting_serve_set ";
            sql += " where id in(:msList) ";
            paramMap.put("msList", msList);
            sql += " ORDER BY sort_no asc,createdDate desc";
            
            List menuTree = super.getQueryByNativeSQL(sql.toString(), paramMap).getResultList();
            
            StringBuffer str = new StringBuffer("");
            str.append("[");
            for (int i = 0; i < menuTree.size(); i++) {
                str.append((new StringBuilder()).append("{\"id\":\"").append(((Object[]) menuTree.get(i))[0])
                        .append("\",\"pId\":\"").append("\",\"name\":\"").append(((Object[]) menuTree.get(i))[1])
                        .append("\"},"));
            }
            
            String str1 = str.toString();
            if (str1.endsWith(","))
                str1 = str1.substring(0, str1.length() - 1);
            str1 = (new StringBuilder()).append(str1).append("]").toString();
            return str1;
        }else{
            return "[]";
        }
    }

    /**
     * 根据会议室id查询会议服务列表
     * @author zhaoyh
     * @date 2018年3月28日 下午9:47:55
     */
    public List<Object[]> getServeByBoardRoom(String corpId, String boardroomId) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        List<Object> menuTree = new ArrayList<Object>();
        BoardroomSet boardroomSet = this.boardroomSetService.findOne(boardroomId);
        List<String> msList = new ArrayList<String>();
        if(boardroomSet != null){
            String meetingServer = boardroomSet.getMeetingServe();
            if(StringUtils.isNoneEmpty(meetingServer)){
                for(String ms:meetingServer.split(",")){
                    msList.add(ms);
                }
            }
        }
        List<Object[]> serves = new ArrayList<>();
        if(msList!=null &&msList.size()>0){
            String sql = "select id,name from oa_meeting_serve_set ";
            sql += " where id in(:msList) ";
            paramMap.put("msList", msList);
            sql += " ORDER BY sort_no asc,createdDate desc";

            serves = super.getQueryByNativeSQL(sql.toString(), paramMap).getResultList();
        }
        return serves;
    }

	/**
	 * 根据会议室id查询会议服务列表
	* @author zhaoyh  
	* @date 2018年3月28日 下午9:47:55   
	*/
	public List getBoardRoomServeTreeDataList(String corpId, String boardroomId) {
		List<Object> menuTree = new ArrayList<Object>();
        List<Object[]>  serves =  this.getServeByBoardRoom(corpId, boardroomId);
        if(serves !=null && serves.size()>0){
            for (int i = 0; i < serves.size(); i++) {
            	Map<String,Object> map = new HashMap<String,Object>();
            	map.put("value", ((Object[]) serves.get(i))[0]);
            	map.put("text", ((Object[]) serves.get(i))[1]);
            	menuTree.add(map);
            }
            return menuTree;
        }else{
            return menuTree;
        }
	}

    /**
     * 根据会议室id查询会议服务列表
     * @author zhaoyh
     * @date 2018年3月28日 下午9:47:55
     */
    public List getBpmServeTreeDataList(String corpId, String boardroomId) {
        List<Object> menuTree = new ArrayList<Object>();
        List<Object[]>  serves =  this.getServeByBoardRoom(corpId, boardroomId);
        if(serves !=null && serves.size()>0){
            for (int i = 0; i < serves.size(); i++) {
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("value", ((Object[]) serves.get(i))[0]);
                map.put("name", ((Object[]) serves.get(i))[1]);
                menuTree.add(map);
            }
            return menuTree;
        }else{
            return menuTree;
        }
    }

	public void clearData(String corpId) {
		this.dao.delServeSetSet(corpId, "1");
	}

    /**
     * 获取服务名称
     * @param idStr
     * @return
     */
	public String getServeName(String idStr){
	    String name = "";
	    if(StringUtils.isNotBlank(idStr)){
	        String[] ids = idStr.split(",");
	        List<String> idList = new ArrayList<>();
            for (String id: ids) {
                idList.add(id);
            }
	        List<ServeSet> serveSets = this.dao.getServeSetByIds(idList);
	        if(serveSets!=null && serveSets.size()>0){
                for (ServeSet serve: serveSets) {
                    if(serve != null){
                        name += serve.getName()+",";
                    }
                }
                if(name != ""){
                    name = name.substring(0, name.length()-1);
                }
            }
        }
        return name;
    }
	
	public void initData(String corpId) {
		List<ServeSet> initServe = this.dao.getServeSetSet(corpId,"1"); 
		if(CollectionUtils.isEmpty(initServe)){
			List<ServeSet> serveSets = this.dao.getServeSetSet("0","1"); 
			if(serveSets!=null && serveSets.size()>0){
				List<ServeSet> newSetList = new ArrayList<ServeSet>();
				for(ServeSet ss : serveSets){
					ServeSet serveSet = new ServeSet();
					serveSet.setCorpId(corpId);
					serveSet.setIsInit("1");
					serveSet.setName(ss.getName());
					serveSet.setSortNo(ss.getSortNo());
					serveSet.setDescription(ss.getDescription());
					newSetList.add(serveSet);
				}
				this.dao.saveAll(newSetList);
			}
		}
	}
	
	public Map<String, String> getServeSetData(){
		List<ServeSet> serveSets = this.findAll();
		if(CollectionUtils.isNotEmpty(serveSets)) {
			Map<String, String> result = new HashMap<String,String>();
			for(ServeSet ss : serveSets) {
				result.put(ss.getId(), ss.getName());
			}
			return result;
		}
		return null;
	}
	
	/**
 	 * 获取移动参会参数
 	 * @param meetingApplyId
 	 * @return
 	 */
 	public Map getQsMeetingInfoById(String meetingApplyId) {
    	logger.debug("-----------------getQsMeetingInfoById-------");
        StringBuffer sql = new StringBuffer("select emceeUser,conferenceId,pcode1,pcode2 "
        		+ " from oa_meeting_qs where meetingApplyId =:meetingApplyId ");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("meetingApplyId", meetingApplyId);
        List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
        if(list!=null&&list.size()>0) {
           return (Map) list.get(0);
        }else {
        	return null;
        }
    }
 	
 	/**
 	 * 获取全时会议系统注册信息
 	 * @param userId
 	 * @return
 	 */
 	public Map getQsUserInfoById(String userId) {
    	logger.debug("-----------------getQsUserInfoById-------");
        StringBuffer sql = new StringBuffer("select qsuserName,qsemail from oa_meeting_qsuser where userId=:userId ");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", userId);
        List<Map> list = super.findByListNativeQuery(sql.toString(), "",paramMap);
        if(list!=null&&list.size()>0) {
           return (Map) list.get(0);
        }else {
        	return null;
        }
    }
}